package com.ccb.sc.common.rule.medal.rules;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ccb.sc.common.modules.member.entity.MemberMedal;
import com.ccb.sc.common.modules.member.enums.MedalType;
import com.ccb.sc.common.modules.member.service.MemberMedalService;
import com.ccb.sc.common.rule.medal.fact.MedalFact;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author ken
 * @version 1.0
 * @date 2022/8/26 0:25
 */
@Component
public abstract class AbstractMedalRule {

    @Autowired
    @Lazy
    private MemberMedalService memberMedalService;

    protected boolean getCondition(MedalFact fact, MedalType medalType) {
        boolean condition = false;
        if (fact.getExchangeOrders() >= medalType.getExchangeOrders()) {
            fact.setLightUpReason(String.format("订单转换次数达到%d次", medalType.getExchangeOrders()));
            condition = true;
        }
        if (fact.getResevers() >= medalType.getReserves()) {
            fact.setLightUpReason(String.format("预约直播次数达到%d次", medalType.getReserves()));
            condition = true;
        }
        if (condition) {
            // 判断是否有获得勋章
            long count = this.memberMedalService.count(Wrappers.<MemberMedal>lambdaQuery()
                    .eq(MemberMedal::getMemberId, fact.getMemberId())
                    .eq(MemberMedal::getMedalType, medalType));
            return count == 0;
        }
        return false;
    }

    protected void saveMedal(Long memberId, MedalType medalType, String lightUpReason) {
        MemberMedal memberMedal = new MemberMedal();
        memberMedal.setMemberId(memberId);
        memberMedal.setMedalType(medalType);
        memberMedal.setIsShow(false);
        memberMedal.setLightUpReason(lightUpReason);
        memberMedal.setLightUpTime(LocalDateTime.now());
        this.memberMedalService.save(memberMedal);
    }

}

